import type { FC } from 'react';
import { Form, Input, message } from 'antd';
import { useNavigate, Link } from 'react-router-dom';
import { useSafeState, useMemoizedFn } from 'ahooks';
import CardLayout from '@/components/CardLayout';
import { signIn } from '@/libs/cognitoClient';
import tokenCenter from '@/helpers/token';
import styles from './styles.module.less';

const Signin: FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useSafeState(false);

  const onSignin = useMemoizedFn(async () => {
    const values = await form.validateFields();
    setLoading(true);
    try {
      const result = await signIn({
        userName: values.userName,
        password: values.password
      });
      tokenCenter.setToken(result);
      requestAnimationFrame(() => navigate('/'));
    } catch (err: any) {
      message.error(err.message);
    } finally {
      setLoading(false);
    }
  });

  return (
    <CardLayout
      loading={loading}
      onSubmit={onSignin}
      buttonText="Sign in"
      title="Welcome to aibot"
      footer={
        <div className={styles.footer}>
          <div className={styles.footer_label}>
            {`Don't have an account yet? `}
          </div>
          <Link to="/signup">Sign up</Link>
        </div>
      }
    >
      <Form size="large" form={form}>
        <Form.Item
          name="userName"
          initialValue="578091306@qq.com"
          rules={[
            {
              required: true,
              message: 'Please enter email'
            },
            {
              type: 'email',
              message: 'Please enter the correct email address'
            }
          ]}
        >
          <Input placeholder="Email" />
        </Form.Item>
        <Form.Item
          name="password"
          initialValue="Huaxin19jt."
          rules={[
            {
              required: true,
              message: 'Please enter password'
            }
          ]}
        >
          <Input.Password placeholder="Password" />
        </Form.Item>
      </Form>
    </CardLayout>
  );
}

export default Signin;